/**
 * 自定义 request 网络请求工具,基于axios
 * @author LuoXiYang
 */
import axios from "axios";
import { Notify, Toast } from "vant";
import storage from "@/utils/storage";

const serverCodeMessage = {
  200: "服务器成功返回请求的数据",
  // 400: 'Bad Request',
  401: "Unauthorized",
  403: "Forbidden(无权限)",
  404: "Not Found",
  500: "服务器发生错误，请检查服务器(Internal Server Error)",
  502: "网关错误(Bad Gateway)",
  503: "服务不可用，服务器暂时过载或维护(Service Unavailable)",
  504: "网关超时(Gateway Timeout)",
};

/**
 * 异常处理程序
 */
const errorHandler = (error) => {
  const { response } = error;
  if (response && response.status) {
    const { status, request } = response;
    const errorText = serverCodeMessage[response.status] || response.statusText;

    Notify({
      type: "warning",
      message: `请求错误${status}:\n${request.responseURL}\n${errorText}`,
    });
  } else if (!response) {
    Notify({
      type: "warning",
      message: "您的网络发生异常，无法连接服务器",
    });
  }
  return Promise.reject(error);
};

/**
 * 配置request请求时的默认参数
 */
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  // withCredentials: true, // 当跨域请求时发送cookie
  timeout: 300000, // 请求超时时间,5000(单位毫秒) / 0 不做限制
});

/**
 * 请求前
 * 请求拦截器
 */
request.interceptors.request.use(
  async (config) => {
    const token = await storage.get("token");
    const userInfo = await storage.get("userInfo");

    if (config.url === "/api/tollman/find-one") {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    }

    // if (token) config.headers["token"] = token;

    console.log(token, "打印");
    if (token) config.headers["Authorization"] = "Bamboo " + token;
    if (userInfo) {
      config.headers["parkCode"] = userInfo.parkCode ? userInfo.parkCode : "";
      if (config.method === "post" || config.method === "put") {
        config.data["parkCode"] = config.data["parkCode"]
          ? config.data["parkCode"]
          : userInfo.parkCode;
      } else {
        config.params["parkCode"] = config.params["parkCode"]
          ? config.params["parkCode"]
          : userInfo.parkCode;
      }
    }
    return config;
  }
  /* error=> {} */ // 已在 export default catch
);

/**
 * 请求后
 * 响应拦截器
 */
request.interceptors.response.use(
  async (response) => {
    const res = response.data;
    const { code, msg } = res;
    if (code !== 200) Toast(msg);
    return res;
  }
  /* error => {} */ // 已在 export default catch
);

export default function (config) {
  return request(config)
    .then((response) => response)
    .catch((error) => errorHandler(error));
}
